package com.xyhuo.leetcode.november;

/**
 * 最大子数组和
 * https://leetcode.cn/problems/maximum-subarray/
 *
 * @time 2023/11/20
 */
public class MaxSubArray {

    public int maxSubArray(int[] nums) {
        if (nums.length == 0) {
            return 0;
        }
        int length = nums.length;
        int[] dp = new int[length];
        dp[0] = nums[0];
        for (int i = 1; i < length; i++) {
            if (dp[i - 1] > 0) {
                dp[i] = dp[i - 1] + nums[i];
            } else {
                dp[i] = nums[i];
            }
        }
        int result = dp[0];
        for (int i = 1; i < length; i++) {
            if (dp[i] > result) {
                result = dp[i];
            }
        }
        return result;

    }
}
